<?php

class Application_Model_Project {

    private $_dbtable;

    public function __construct() {
        $this->_dbtable = new Application_Model_DbTable_Project();
    }

    /**
     * 
     * @param type $data
     * @return type
     */
    public function createProjet($data) {
        return $this->_dbtable->insert($data);
    }

    /**
     * 
     * @param type $id
     * @return type
     */
    public function getById($id) {
        $select = $this->_dbtable->select();
        $select->where("id = ?", $id);
        $fetchAll = $this->_dbtable->fetchAll($select);
        $formatData = $this->formatData($fetchAll[0]);
        return $formatData;
    }

    /**
     * 
     * @param type $userId
     * @return array
     */
    public function fetchAll($userId = 0) {
        $select = $this->_dbtable->select();
        if ($userId != 0) {
            $select->where("user_id = ?", $userId);
        }
        $fetchAll = $this->_dbtable->fetchAll($select);
        $array = array();
        foreach ($fetchAll as $data) {
            array_push($array, $this->formatData($data));
        }
        return $array;
    }

    /**
     * 
     * @param type $data
     * @param type $id
     * @return type
     */
    public function updateData($data, $id) {
        return $this->_dbtable->update($data, "id = $id");
    }

    /**
     * 
     * @param type $data
     */
    private function formatData($data) {
        $djson = json_decode($data['details']);
        $optionsDb = new Application_Model_Options();
        $projectStatus = $optionsDb->getByName("projectStatus");
        $userDb = new Application_Model_Users();
        $class= "alter";
        switch ($data['status']) {
            case 0: #requirement gathering
                $class = "alert";                
                break;
            case 1:#under development
                $class = "alert alert-info";
                break;
            case 2: #completed
                $class = "alert alert-success";
            default:
                break;
        }
        $array = array(
            'id' => $data['id'],
            'name' => $djson->name,
            'projectLink' => $djson->projectLink,
            'description' => $djson->description,
            'userId' => $data['user_id'],
            'user' => $userDb->getById($data['user_id']),
            'status_id' => $data['status'],
            'status' => $projectStatus['details'][$data['status']],
            'status_id' => $data['status'],
            'finalized' => $data['finalized'],
            'class' => $class,
        );
        return $array;
    }

}

